#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/10/25 10:58
# @Author  : Tom_zc
# @FileName: upload_file.py
# @Software: PyCharm
import os
import sys
import time
import click
import logging
import zipfile
import hashlib
from pathlib import Path

CURR_DIR = Path(__file__).resolve()
ROOT_DIR = CURR_DIR.parent.parent.parent.parent
sys.path.append(ROOT_DIR.as_posix())

from scripts.utils.common import func_retry
from scripts.utils.obs_helper import ObsHelper

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


def generate_sha256_file(filename):
    file_path = Path(filename)
    sha256_path = file_path.parent / (file_path.stem + '.sha256')

    try:
        if not file_path.is_file():
            logging.error(f"文件不存在: {filename}")
            sys.exit(1)
        sha256_hash = hashlib.sha256()
        with file_path.open('rb') as f:
            for chunk in iter(lambda: f.read(8192), b''):
                sha256_hash.update(chunk)

        checksum = sha256_hash.hexdigest()
        sha256_path.write_text(f"{checksum} *{file_path.name}\n")

        return str(sha256_path), sha256_path.name
    except Exception as e:
        logging.error(f"生成sha256文件失败: {e}")
        sys.exit(1)


class PipeLineLogHelper:

    def __init__(self, ak, sk, obs_endpoint, obs_bucket_name):
        self.obs_helper = ObsHelper(ak, sk, obs_endpoint)
        self.obs_bucket_name = obs_bucket_name
        self.date = time.localtime(time.time())

    def upload_obs(self, prefix_path, path):
        files_with_custom_names = [(os.path.dirname(os.path.abspath(__file__)) + '/LICENSE.txt', 'LICENSE.txt'),
                                   (path, path.name)]

        # add the sha256 file
        sha_path, sha_filename = generate_sha256_file(path)
        files_with_custom_names.append((sha_path, sha_filename))

        self.upload(files_with_custom_names, prefix_path)

    @func_retry()
    def upload(self, files_with_custom_names, prefix_path):
        for original_path, custom_name in files_with_custom_names:
            if os.path.exists(original_path):
                output_key = "{}{}".format(prefix_path, custom_name)
                self.obs_helper.upload_file(self.obs_bucket_name, output_key, original_path)
            else:
                print(f'File {original_path} does not exist.')


@click.command()
@click.option("--ak")
@click.option("--sk")
@click.option("--obs_endpoint")
@click.option("--bucket_name")
@click.option("--prefix_path")
@click.option("--release")
def main(ak, sk, obs_endpoint, bucket_name, prefix_path, release):
    logging.info("=" * 20 + "start to upload the log to obs" + "=" * 20)

    if not all([ak, sk, obs_endpoint, bucket_name, prefix_path, release]):
        logging.info("Lack of params:{}, Please check.".format(release))
        sys.exit(-1)

    release_full_path = None
    for path in os.listdir(release):
        if path.endswith(".zip"):
            logging.info("find the zip package:{}".format(path))
            release_full_path = Path(os.path.join(release, path))
            break

    pipeline_log_helper = PipeLineLogHelper(ak, sk, obs_endpoint, bucket_name)
    if release_full_path and os.path.exists(release_full_path):
        pipeline_log_helper.upload_obs(prefix_path, release_full_path)
    else:
        logging.info("The file:{} is not exists.".format(release_full_path))

    logging.info("=" * 20 + "end to uploaded the obs" + "=" * 20)


if __name__ == '__main__':
    main()
